<template>
  <div class="login">
    <div class="login-box">
      <h1>叩丁狼商品管理系统</h1>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            v-model="ruleForm.username"
            placeholder="请输入用户名"
            autocomplete="off"
            :prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="请输入密码"
            autocomplete="off"
            :prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { UserFilled, Lock } from "@element-plus/icons-vue";
import { loginApi } from "@/api";
import { useRouter } from "vue-router";
const ruleFormRef = ref<FormInstance>();
const router = useRouter();
const ruleForm = reactive<ILoginForm>({
  username: "admin",
  password: "123456",
});

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    // 人家提供了很多种方式来进行数据校验
    // { pattern: /^[1]\d{10}$/, message: "请输入正确的手机号", trigger: "blur" },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  // 进入提交的点击之后，是否还需要再次进行校验 ? 要 !!!
  // 这个时候需要调用 表单实例的一个方法 validate 进行校验
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 校验通过
      // console.log("submit!");
      loginApi(ruleForm).then((res) => {
        if (res.code == 200) {
          // 提示用户 -- 记得在全局引入 element 的样式
          ElMessage.success("登录成功");
          // 保存token , tokenHead + token 其实才是正规的存token的方式
          localStorage.setItem("token", res.data.tokenHead + res.data.token);
          // 跳转到首页
          router.push("/");
        }
      });
    } else {
      // 校验不通过
      console.log("error submit!");
      // 表单校验不通过，需要返回false
      return false;
    }
  });
};
</script>

<style scoped lang="less">
.login {
  background-color: #2d3a4b;
  height: 100vh;
  color: #fff;
  .login-box {
    width: 400px;
    margin: auto;
    transform: translateY(200px);
    h1 {
      text-align: center;
      padding: 50px 0;
    }
    .el-button--primary {
      width: 100%;
    }
  }
}
</style>
